<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Ruby Overriding Methods: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby study notes,ruby overriding,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/ruby_overriding_methods.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">


            <div id="main">

                <div id="main-inner"> <a name="TemplateInfo"></a>
                <h1>Ruby Overriding Methods</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_inheritance.html">&lt;Inheritance | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_overloading_methods.html">Overloading Methods&gt;</a>
                  </strong>
                </p>

                <p><strong>Method overriding</strong>, in object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass <em>overrides</em> (replaces) the implementation in the superclass.</p>

                <p>Here's an example <strong>p037xmtdovride.rb</strong>:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class A
                  def a
                    puts 'In class A'
                  end
                end

                class B &lt; A
                  def a
                    puts 'In class B'
                  end
                end

                b = B.new
                b.a
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The method a in class B overrides the method a in class A.</p>

                <h3>Usage of super</h3>

                <p>The way <strong>super</strong> handles arguments is as follows:</p>

                <ul>
                  <li>When you invoke <strong>super</strong> with no arguments Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking <strong>super</strong>. It automatically forwards the arguments that were passed to the method from which it's called.</li>
                  <li>Called with an empty argument list - <strong>super()</strong>-it sends no arguments to the higher-up method, even if arguments were passed to the current method.</li>
                  <li>Called with specific arguments - <strong>super(a, b, c)</strong> - it sends exactly those arguments.</li>
                </ul>

                <p>An example (<strong>p038bicycle.rb</strong>) from Ruby for Rails book highlights this:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class Bicycle
                  attr_reader :gears, :wheels, :seats
                  def initialize(gears = 1)
                    @wheels = 2
                    @seats = 1
                    @gears = gears
                  end
                end

                class Tandem &lt; Bicycle
                  def initialize(gears)
                    super
                    @seats = 2
                  end
                end
                t = Tandem.new(2)
                puts t.gears
                puts t.wheels
                puts t.seats
                b = Bicycle.new
                puts b.gears
                puts b.wheels
                puts b.seats
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p038bicycle.rb
                2
                2
                2
                1
                2
                1
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>We shall be talking in depth about <strong><a href="/satishtalim/ruby_access_control.html">attr_reader</a></strong> later.</p>

                <h3>Redefining Methods</h3>

                <p>(Adapted from David Black's book, <em>Ruby For Rails</em>)</p>

                <p>Nothing stops you from defining a method twice. Program <strong>p038or.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class OR
                  def mtd
                    puts "First definition of method mtd"
                  end
                  def mtd
                    puts "Second definition of method mtd"
                  end
                end
                OR.new.mtd
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>What happens when we call mtd on an instance of OR? Let's find out:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                OR.new.mtd
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The printed result is the Second definition of method mtd. The second definition has prevailed: We see the output from that definition, not from the first. <em>Nothing stops you from defining a method twice, however the new version takes precedence</em>.</p>

                <h3>Abstract class</h3>

                <p>In Ruby, we can define an <em>abstract</em> class that invokes certain undefined "abstract" methods, which are left for subclasses to define. For example:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # This class is abstract; it doesn't define hello or name
                # No special syntax is required: any class that invokes methods
                # that are intended for a subclass to implement is abstract
                class AbstractKlass
                  def welcome
                    puts "#{hello} #{name}"
                  end
                end

                # A concrete class
                class ConcreteKlass &lt; AbstractKlass
                  def hello; "Hello"; end
                  def name; "Ruby students"; end
                end

                ConcreteKlass.new.welcome # Displays "Hello Ruby students"
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_inheritance.html">&lt;Inheritance | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_overloading_methods.html">Overloading Methods&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
